package jh.com.jhappbf.dispatchcar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.ab.activity.AbActivity;
import com.ab.fragment.AbDialogFragment;
import com.ab.fragment.AbDialogFragment.AbDialogOnLoadListener;
import com.ab.util.AbDialogUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.pullview.AbPullToRefreshView;
import com.ab.view.pullview.AbPullToRefreshView.OnFooterLoadListener;
import com.ab.view.pullview.AbPullToRefreshView.OnHeaderRefreshListener;
import com.ab.view.titlebar.AbTitleBar;
import com.android.volley.Request.Priority;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.baoyz.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import jh.com.jhappbf.R;

import jh.com.jhappbf.httputils.VolleyCallWebService;
import jh.com.jhappbf.httputils.VolleySingleton;
import jh.com.jhappbf.model.DispatchModel;
import jh.com.jhappbf.ui.State;
import jh.com.jhappbf.utils.JsonHelper;
import jh.com.jhappbf.utils.PixAndDpUtil;
import jh.com.jhappbf.view.PointDialog;

public class DispatchCarQuery extends AbActivity   {
    private View  mNetErrorView;
    private View mDataContentView;
    private AbPullToRefreshView mRefreshView;
    private SwipeMenuListView mList;
    private Button mTryAgin;
    private Context mAppContext;
    private List<JSONObject>mData;
    private List<JSONObject>mNewData;
    private myBaseAdapter  mAdapter;
    private AbDialogFragment mDialogFragment;
    private int mCurrentPage = 1;
    private int mPageSize = 30;
    private Map<String, String> mStateMap ;
    private final int UPDATEDISPATCH = 0X0001;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        mDataContentView = inflater.inflate(R.layout.dispatch_car_query_activity, null);
        mNetErrorView = inflater.inflate(R.layout.net_error_activity,null);
        setAbContentView(mDataContentView);
        AbTitleBar mAbTitleBar = this.getTitleBar();
        mAbTitleBar.setTitleText(R.string.dispatch_car_query_title);
        mAbTitleBar.setLogo(R.drawable.button_selector_back);
        mAbTitleBar.setTitleBarBackground(R.drawable.top_bg);
        mAbTitleBar.setTitleTextMargin(10, 0, 0, 0);
        mAbTitleBar.setLogoLine(R.drawable.line);
        initView();
    }

    /**
     * 初始化
     */
    private void initView()
    {
        mList = (SwipeMenuListView) mDataContentView.findViewById(R.id.dispatch_query_listView);
        mRefreshView = (AbPullToRefreshView) mDataContentView.findViewById(R.id.dispatch_query_pullToRefreshView);
        mTryAgin = (Button) mNetErrorView.findViewById(R.id.network_error_btn);
        mAppContext = getApplicationContext();
        mData = new ArrayList<JSONObject>();
        mNewData = new ArrayList<JSONObject>();
        mAdapter = new myBaseAdapter();
        mList.setAdapter(mAdapter);
        SwipeMenuCreator Creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {

                SwipeMenuItem item = new SwipeMenuItem(DispatchCarQuery.this
                        .getApplicationContext());
                item.setTitle("查 看");
                item.setBackground(new ColorDrawable(Color
                        .rgb(0xC9, 0xC9, 0xCE)));
                item.setWidth(PixAndDpUtil.dp2px(80, DispatchCarQuery.this
                        .getApplicationContext()));
                item.setTitleSize(18);
                item.setTitleColor(Color.WHITE);
                menu.addMenuItem(item);

//                SwipeMenuItem deleteItem = new SwipeMenuItem(DispatchCarQuery.this
//                        .getApplicationContext());
//                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
//                        0x3F, 0x25)));
//                deleteItem.setWidth(PixAndDpUtil.dp2px(80, DispatchCarQuery.this
//                        .getApplicationContext()));
//                deleteItem.setTitleSize(18);
//                deleteItem.setIcon(R.drawable.history_item_delete);
//                deleteItem.setTitleColor(Color.WHITE);
//                menu.addMenuItem(deleteItem);
            }
        };
        mList.setMenuCreator(Creator);
        mList.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int index, SwipeMenu arg1, int btnIndex) {
                JSONObject obj = mData.get(index);
                String id = obj.optString("派车单号");
//                if(btnIndex == 1)
//                {
//                    deleteOperate(id,index);
//                }
//                else {
                    updateDispatch(index);
//                }
            }
        });
        mStateMap = new HashMap<String, String>();
        mStateMap.put("0", "已派车");
        mStateMap.put("1", "已审核");
        mStateMap.put("2", "抽样");
        mStateMap.put("4", "化验");
        mStateMap.put("5", "一次过磅");
        mStateMap.put("6", "二次过磅");
        mStateMap.put("a", "出厂");
        mTryAgin.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                setAbContentView(mDataContentView);
                LoadFirst();
            }
        });

        mRefreshView.setOnHeaderRefreshListener(new OnHeaderRefreshListener() {

            @Override
            public void onHeaderRefresh(AbPullToRefreshView view) {
                refreshTask();
            }
        });

        mRefreshView.setOnFooterLoadListener(new OnFooterLoadListener() {

            @Override
            public void onFooterLoad(AbPullToRefreshView view) {
                loadMore();
            }
        });

		/*mList.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, final View view,
					final int position, long id) {
				PopupMenu menu = new PopupMenu(DispatchCarQuery.this, view);
				getMenuInflater().inflate(R.menu.dispatch_context_menu, menu.getMenu());
				menu.setOnMenuItemClickListener(new OnMenuItemClickListener() {

					@Override
					public boolean onMenuItemClick(MenuItem item) {
						ViewHolder holder = (ViewHolder) view.getTag();
						String id= holder.id;

						return true;
					}
				});
				menu.show();
				return true;
			}
		});*/
        LoadFirst();
    }


    /**
     * 删除派车
     * @param id
     * @param position
     */
    private void deleteOperate(String id,int position)
    {
        if(TextUtils.isEmpty(id))
        {
            AbToastUtil.showToast(DispatchCarQuery.this, "派车单号为空,删除失败!");
        }
        else
        {
            deleteDispatch(id,position);
        }
    }

    /**
     * 修改派车单
     * @param index
     */
    private void updateDispatch(int index) {
        JSONObject obj = mData.get(index);
        DispatchModel model = new DispatchModel();
        model.setDispatchId(obj.optString("派车单号"));
        model.setPlanId(obj.optString("计划单号"));
        model.setPlateNumber(obj.optString("车号"));
        model.setCargoname(obj.optString("货名"));
        model.setSpec(obj.optString("规格"));
        model.setType(obj.optString("类型"));
        model.setPrice(obj.optString("单价"));
        model.setSender(obj.optString("发货"));
        model.setReceiver(obj.optString("收货"));
        model.setUnit(obj.optString("单位"));
        Intent i = new Intent(DispatchCarQuery.this, DispatchCarAdd.class);
        i.putExtra("model", model);
        i.putExtra("flag", "update");
        startActivityForResult(i, UPDATEDISPATCH);
    }

    /**
     * 删除
     * @param id 派车单编号
     * @param index 数据的索引
     */
    private  void deleteDispatch(String id,final int index)
    {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.drawable.ic_load,
                "删除中,请稍等...");
        mDialogFragment.setCancelable(false);
        String methodName = "deleteDispatch";
        ArrayList<String> param = new ArrayList<String>();
        ArrayList<String> value = new ArrayList<String>();
        param.add("id");
        value.add(id);
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {
                AbDialogUtil.removeDialog(DispatchCarQuery.this);
                List<JSONObject> data = JsonHelper.getJsonObjects(response);
                if (data != null && data.size() > 0) {
                    JSONObject obj = data.get(0);
                    String result = obj.optString("result");
                    String memo = obj.optString("memo");
                    if(result.equals("true"))
                    {
                        mData.remove(index);
                        mAdapter.notifyDataSetChanged();
                    }
                    AbToastUtil.showToast(DispatchCarQuery.this, memo);
                }
                else {
                    AbToastUtil.showToast(DispatchCarQuery.this, "删除失败!");
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(DispatchCarQuery.this);
                AbToastUtil.showToast(DispatchCarQuery.this, "删除失败!");
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    /**
     * 第一次加载
     */
    private void LoadFirst() {
        mDialogFragment = AbDialogUtil.showLoadDialog(this, R.drawable.ic_load,
                "查询中,请稍等...");
        mDialogFragment.setCancelable(false);
        mDialogFragment.setAbDialogOnLoadListener(new AbDialogOnLoadListener() {

            @Override
            public void onLoad() {
                refreshTask();
            }
        });
    }

    /**
     * 上拉刷新
     */
    private void refreshTask()
    {
        mCurrentPage = 1;
        String methodName = "queryDispatch";
        ArrayList<String> param = new ArrayList<String>();
        ArrayList<String> value = new ArrayList<String>();
        param.add("strCurrentPage");
        param.add("strPageSize");
        param.add("userName");
        value.add(String.valueOf(mCurrentPage));
        value.add(String.valueOf(mPageSize));
        value.add(String.valueOf(State.mName));
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {

                AbDialogUtil.removeDialog(DispatchCarQuery.this);
                mDialogFragment.dismiss();
                mRefreshView.onHeaderRefreshFinish();
                List<JSONObject> data = JsonHelper.getJsonObjects(response);
                if (data != null) {
                    mData = data;
                    if(mPageSize == data.size())
                    {
                        mCurrentPage++;
                    }
                    else {
                        mNewData = data;
                    }
                    if(mData.size() == 0)
                    {
                        Toast.makeText(DispatchCarQuery.this, "无派车数据!", Toast.LENGTH_SHORT).show();
                    }
                    mAdapter.notifyDataSetChanged();
                }
                else
                {
                    Toast.makeText(DispatchCarQuery.this, "无派车数据!", Toast.LENGTH_SHORT).show();
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(DispatchCarQuery.this);
                mRefreshView.onHeaderRefreshFinish();
                setAbContentView(mNetErrorView);
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }


    /**
     * 下拉加载
     */
    private void loadMore()
    {
        String methodName = "queryDispatch";
        ArrayList<String> param = new ArrayList<String>();
        ArrayList<String> value = new ArrayList<String>();
        param.add("strCurrentPage");
        param.add("strPageSize");
        param.add("userName");
        value.add(String.valueOf(mCurrentPage));
        value.add(String.valueOf(mPageSize));
        value.add(String.valueOf(State.mName));
        Listener<String> listener = new Listener<String>() {
            @Override
            public void onResponse(String response) {

                AbDialogUtil.removeDialog(DispatchCarQuery.this);
                mRefreshView.onFooterLoadFinish();
                List<JSONObject> data = JsonHelper.getJsonObjects(response);
                if (data != null) {

                    if(mNewData.size() < mPageSize && mNewData.size() > 0)
                    {
                        mData.removeAll(mNewData);
                        mNewData.clear();
                    }

                    if(data.size() == mPageSize)
                    {
                        mData.addAll(data) ;
                        mCurrentPage++;
                    }
                    else {
                        mNewData = data;
                        mData.addAll(data) ;
                    }
                    mAdapter.notifyDataSetChanged();
                }
            }
        };

        ErrorListener errorListener = new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                AbDialogUtil.removeDialog(DispatchCarQuery.this);
                mRefreshView.onFooterLoadFinish();
                setAbContentView(mNetErrorView);
            }
        };

        VolleyCallWebService webService = new VolleyCallWebService(methodName,
                param, value, listener, errorListener, Priority.NORMAL);
        VolleySingleton.getVolleyInstance(getApplicationContext()).addRequest(
                webService);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        if(intent != null)
        {
            boolean value = intent.getBooleanExtra("updateSate", false);
            if(value)
            {
                LoadFirst();
            }
        }
    }


    class myBaseAdapter extends BaseAdapter
    {
        @Override
        public int getCount() {
            return mData.size();
        }

        @Override
        public Object getItem(int position) {
            return mData.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if(convertView == null)
            {
                holder = new ViewHolder();
                LayoutInflater inflater =  (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.dispatch_car_query_list_item, null);
                holder.img = (ImageView) convertView.findViewById(R.id.dispatch_car_query_list_item_img);
                holder.plateNumber = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_platenum);
                holder.cargoname  = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_cargoname);
                holder.states= (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_state);
                holder.stime = (TextView) convertView.findViewById(R.id.dispatch_car_query_list_item_times);
                convertView.setTag(holder);
            }
            else
            {
                holder = (ViewHolder) convertView.getTag();
            }
            JSONObject object= mData.get(position);
            holder.id = object.optString("派车单号");
            holder.img.setBackgroundResource(R.drawable.dispatch_car_query_item_ico);
            holder.plateNumber.setText("车号: "+object.optString("车号"));
            holder.cargoname.setText("货名: "+object.optString("货名"));
            String state = object.optString("状态");
            String overTime = object.optString("过期");
            if(mStateMap.containsKey(state))
            {
                holder.states.setText("状态: "+mStateMap.get(state));
            }

            if(!TextUtils.isEmpty(overTime) && overTime.equals("1"))
            {
                holder.states.setText("状态:过期");
            }

            holder.stime.setText("派车时间: "+object.optString("时间"));
            return convertView;
        }
    }

    class ViewHolder
    {
        public String id ;
        public ImageView img;
        public TextView plateNumber;
        public TextView cargoname;
        public TextView states;
        public TextView stime;
    }
}
